package com.sishu.service.impl;

import com.sishu.mapper.CardlibraryMapper;
import com.sishu.pojo.Cardlibrary;
import com.sishu.service.CardlibraryService;
import com.sishu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class CardlibraryServiceimpl implements CardlibraryService {


    @Resource
    private CardlibraryMapper cardlibraryMapper;


    private Set<Integer> usedQuestionIds = Collections.synchronizedSet(new HashSet<>());


    @Override
    public Result getrandomcard(String cardtype) {
        if (cardtype == null || cardtype.isEmpty()) {
            return new Result<>(500, "参数错误", false);
        }

        //List<Cardlibrary> allcards = cardlibraryMapper.selcetAll();//查询数据库中所有的题目放到一个list中
        List<Cardlibrary> allcards = cardlibraryMapper.selcetbycardtype(cardtype);

        log.info("allcards=" + allcards);
        if (CollectionUtils.isEmpty(allcards)) {//如果数据库中没有数据那么会返回题库为空
            return new Result<>(500, "题库为空", false);
        }

        List<Cardlibrary> availableCards = new ArrayList<>();//存储未被使用过的题目
        for (Cardlibrary card : allcards) {
            if (!usedQuestionIds.contains(card.getCardId())) {//遍历 allTikus 列表，检查每个题目的 questionId 是否在 usedQuestionIds 集合中
                availableCards.add(card);//如果 questionId 不在 usedQuestionIds 中，将该题目添加到 availableTikus 列表中
            }
        }

        if (availableCards.isEmpty()) {
            // 所有题目都已使用过，清空已使用的集合
            usedQuestionIds.clear();
            availableCards.addAll(allcards);
        }

        // 随机选择一个题目
        int randomIndex = ThreadLocalRandom.current().nextInt(availableCards.size());
        Cardlibrary selectedCard = availableCards.get(randomIndex);


        // 记录已使用的 questionId
        usedQuestionIds.add(selectedCard.getCardId());

        return new Result<>(200,"data", "随机题目获取成功", selectedCard,true);
    }

    @Override
    public Result insertall(List<Cardlibrary> cardlibraryList) {

        for (Cardlibrary cardlibrary : cardlibraryList) {

            cardlibraryMapper.insert(cardlibrary);
        }
        return new Result<>(202,"添加成功",true);
    }


}
